package com.bicon.botu.mall.component.component;


import com.bicon.botu.mall.component.entity.SearchStatistics;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;

/**
 * 定时归零日周月统计数据
 *
 * @Author: 张凡
 * @date 2017/9/12 0012 上午 9:52
 */
@Component
@Slf4j
public class CleanSearchStatisticsTimerTask {

    //每日23:59:59时执行一次
    @Scheduled(cron = "0 0 0 * * ?")
    public void updateSearchTimes() {
        //获取当前日期
        LocalDate today = LocalDate.now();
        //由于是0点执行，取到的日期是第二天，需要用前一天的日期判断是否本月或本周最后一天
        today = today.plusDays(-1);
        //获取本月最后一天
        LocalDate lastDayOfThisMonth = today.with(TemporalAdjusters.lastDayOfMonth());
        //获取本周最后一天
        LocalDate lastDayOfThisWeek = today.with(DayOfWeek.SUNDAY);
        SearchStatistics searchStatistics = new SearchStatistics();
        searchStatistics.setDaySearchTimes(0);
        if (today.isEqual(lastDayOfThisMonth) && today.isEqual(lastDayOfThisWeek)) {
            //重置当月、当周
            searchStatistics.setMonthSearchTimes(0);
            searchStatistics.setWeekSearchTimes(0);
        }else if (today.isEqual(lastDayOfThisMonth)) {
            //重置当月
            searchStatistics.setMonthSearchTimes(0);
        }else if (today.isEqual(lastDayOfThisWeek)) {
            //重置当周
            searchStatistics.setWeekSearchTimes(0);
        }
        searchStatistics.update(null);
    }
}
